package com.cai.btautolink

import android.app.Service
import android.bluetooth.BluetoothClass
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.hardware.input.InputManager
import android.os.IBinder
import android.util.Log
import android.view.InputDevice


class MyService : Service() {

    companion object {
        const val TAG = "MyService"
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate")

        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val bluetoothAdapter = bluetoothManager.adapter
        if (bluetoothAdapter.isEnabled) {
            Log.d(TAG, "Bluetooth is enabled")

            var ret = false
            bluetoothAdapter.bondedDevices.forEach {

                when (it.bluetoothClass.majorDeviceClass) {
                    BluetoothClass.Device.Major.PERIPHERAL -> {
                        Log.d(TAG, "已配对外设：${it?.name} $it")
                        if (isBluetoothInputInUse(it)) {
                            ret = true
                        }
                    }
                }
            }

            Log.d(TAG, "ret: $ret")
            if (!ret) {
                startConnectActivity()
            }
        } else {
            Log.d(TAG, "Bluetooth is not enabled")
            startConnectActivity()
        }

        stopSelf()
    }

    private fun startConnectActivity() {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    /**
     * 检查蓝牙输入设备（键盘、鼠标）是否正在使用
     */
    fun isBluetoothInputInUse(device: BluetoothDevice): Boolean {

        val inputManager = getSystemService(INPUT_SERVICE) as InputManager
        val deviceIds = inputManager.inputDeviceIds
        for (deviceId in deviceIds) {
            val inputDevice = inputManager.getInputDevice(deviceId) ?: continue

            // 检查设备是否为蓝牙类型
            Log.d(TAG, "$inputDevice")

            if (inputDevice.name.contains(device.name)) {
                return true
            }
        }
        return false
    }
}